<?php

namespace App\Services;

use App\Http\Resources\School\CheckoutOrderResource;
use App\Models\BookOrder;
use App\Models\BookRule;
use App\Models\Child;
use App\Models\User;
use Illuminate\Support\Facades\Cache;

/**
 * Class CheckOrderService
 * @package Services
 * @author zjw
 * 查验订单服务
 */
class CheckOrderService
{
    public function getOrder(User $user){
        $current = now()->format("H:i:s");
        $rule = $user->school->rule;
        $type = 0;
        if ($current >= $rule->morning_start && $current <= $rule->morning_end) {
            $type = BookRule::EAT_TYPE_BREAKFAST;
        }
        if ($current >= $rule->lunch_start && $current <= $rule->lunch_end) {
            $type = BookRule::EAT_TYPE_LUNCH;
        }
        if ($current >= $rule->dinner_start && $current <= $rule->dinner_end) {
            $type = BookRule::EAT_TYPE_DINNER;
        }
        $orders = BookOrder::query()->whereIn('type', [BookOrder::TYPE_NORMAL, BookOrder::TYPE_ADDITION])->whereHas('rule', function ($query) use ($type) {
            $query->where("eat_type", $type)->where("eat_date", now()->format("Y-m-d"));
        })->where("user_id", $user->id)->whereIn("status",[BookOrder::ORDER_STATUS_MAKING,BookOrder::ORDER_STATUS_COMPLETED, BookOrder::ORDER_STATUS_INIT])->orderBy('type')->with(['review','rule'])->get();
        if (sizeof($orders)> 0) {
            foreach ($orders as $order) {
                BookOrderService::finished($order);
            }
            return CheckoutOrderResource::collection($orders);
        } else {
            return null;
        }
    }
    public function getOrderByChild(Child $child){
        $current = now()->format("H:i:s");
        $rule = $child->user->school->rule;
        $type = 0;
        if ($current >= $rule->morning_start && $current <= $rule->morning_end) {
            $type = BookRule::EAT_TYPE_BREAKFAST;
        }
        if ($current >= $rule->lunch_start && $current <= $rule->lunch_end) {
            $type = BookRule::EAT_TYPE_LUNCH;
        }
        if ($current >= $rule->dinner_start && $current <= $rule->dinner_end) {
            $type = BookRule::EAT_TYPE_DINNER;
        }
        $orders = BookOrder::query()->where('type', BookOrder::TYPE_CHILDREN)->whereHas('rule', function ($query) use ($type) {
            $query->where("eat_type", $type)->where("eat_date", now()->format("Y-m-d"));
        })->where("user_id", $child->user->id)->where('children_id',$child->id)->whereIn("status",[BookOrder::ORDER_STATUS_MAKING,BookOrder::ORDER_STATUS_COMPLETED, BookOrder::ORDER_STATUS_INIT])->orderBy('type')->with(['review','rule'])->get();
        if (sizeof($orders)> 0) {
            foreach ($orders as $order) {
                BookOrderService::finished($order);
            }
            return CheckoutOrderResource::collection($orders);
        } else {
            return null;
        }
    }
}
